package com.tracker;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tracker.util.MasterInformation;
import com.tracker.util.TrackerConnection;



public class TrackConsignment extends HttpServlet {
	
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		TrackerConnection traclerConnection = new TrackerConnection();
		Map<String, String> branches = MasterInformation.getBranches();
		HttpSession session = request.getSession();
		String consignNum = request.getParameter("consignNumber");
		session.setAttribute("history", null);	
		Connection conn = null;
		try{
			conn = traclerConnection.getConnection();
			String outboundQuery = "SELECT ConsignNum,IOMDT,IOMTM,Origin,FromBrn,ToBrn FROM iomoutbound WHERE ConsignNum = ? ORDER BY iomdt ASC ";
			PreparedStatement pstmt = conn.prepareStatement(outboundQuery);
			pstmt.setString(1, consignNum);
			ResultSet rs = pstmt.executeQuery();
			StringBuilder history = new StringBuilder();
			if(rs.next()) {
				session.setAttribute("consignNum", rs.getBigDecimal("ConsignNum"));
				session.setAttribute("bookedDate", rs.getDate("IOMDT"));
				session.setAttribute("bookedTime", rs.getString("IOMTM"));
				session.setAttribute("origin", branches.get(rs.getString("Origin")));
				session.setAttribute("toBrn", rs.getString("ToBrn"));
				history.append("Started from '" + branches.get(rs.getString("FromBrn")) + "' branch and dispatched to '" + branches.get(rs.getString("ToBrn")) +"' branch.");
				while(rs.next()) {
					history.append("<BR/>");
					history.append("Then sent from '" + branches.get(rs.getString("FromBrn")) + "' branch and dispatched to '" + branches.get(rs.getString("ToBrn")) +"' branch.");					
				}
				session.setAttribute("history", history.toString());
				
			} else {
				session.setAttribute("consignNum",null);
			}
			request.getRequestDispatcher("/trackcn.jsp").forward(request, response);
			
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}

}
